// packageA/pages/partsSendAdd/partsSendAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //订单信息
    orderInfo:null,
    //已发配件数量
    sendNumMap:null,
    //配件列表
    loopList:[{
      name: null,
      part: null,
      num: 1,
      remark: null
    }],
    //修改信息回显
    editInfo:null,
    //提交按钮禁用
    disabled:false, 
    //时间选择框
    showTime:false,
    //当前时间
    current: new Date().getTime(),
    //最大时间
    maxDate: new Date().getTime(),  
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    },
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { 
    wx.getUserProfile({
      desc: '为您提供更好的服务',
      success: (res) => {}
    })
    
    //初始化发货时间 
    let deliverTime='editInfo.deliverTime';
    let deliverTimeT='editInfo.deliverTimeT';
    this.setData({
      [deliverTime]: util.timeFormat(new Date()),
      [deliverTimeT]: new Date(),
      current: new Date().getTime(),
      maxDate: new Date().getTime()
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('配件物流传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })  

      //查询订单信息
      this.getOrderInfo();
    }  
  },  

  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let user=app.globalData.userInfo;
    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;
    let loopList=td.loopList;
    let orderInfo=td.orderInfo;
    let operation=orderInfo.operation;  
    
    //物流公司必填
    if(!editInfo.logisticsCompany){
      Toast.fail('请选择物流公司');
      return;
    }

    //物流单号必填
    let trackingNumber=obj.trackingNumber.trim();
    if(!this.formNotEmpty(trackingNumber,'trackingNumberMessage','请输入物流单号')){
      return;
    }

    //运费为数字
    let freight=obj.freight.trim();
    if(freight!='' && freight!=null){
      if(!(/^\d+(\.\d+)?$/.test(freight))){
        this.setData({
          freightMessage: '运费为数字',
          disabled: true
        })
        return;
      }
    }

    //配件必填
    if(loopList.length>=1 && loopList[loopList.length-1].name){
      //操作日志
      loopList.forEach(item => {
        operation.push({
          date: util.timeFormat(new Date()),
          log: '发出'+ item.part.name + item.num + item.part.unit.name,
          user: user.userName
        });
      });
    }else{
      Toast.fail('请选择配件');
      return;
    }

    //新加的物流信息
    let sendList=[];
    if(orderInfo.logisticsParts && orderInfo.logisticsParts.length){
      sendList=orderInfo.logisticsParts;
    }
    let newObj={
      id: new Date().getTime(),
      //物流公司
      logisticsCompany: editInfo.logisticsCompany,
      //物流单号
      trackingNumber: trackingNumber,
      //发货时间:
      deliverTime: editInfo.deliverTimeT,
      //运费
      freight: Number(freight),
      //备注
      remark: obj.remark.trim(),
      //配件
      parts: loopList
    }
    sendList.push(newObj);

    let param={
      //采购单ID
      purchaseOrderId: this.data.paramObj.orderId,
      //采购单号
      purchaseOrderNo: orderInfo.orderNo,
      //采购时间
      purchaseTime: orderInfo.purchasingTime,
      //发货配件列表
      logisticsParts: sendList,
      //操作日志列表
      operation: operation,
      //平台
      appId: [app.globalData.myAppId],  
      //下单人
      buyer: orderInfo.staff,
      //业务员
      salesMan: orderInfo.salesperson,
      //经手人
      clerk: orderInfo.orderPersonnel,
      //当前操作人员
      currentOperationUser:{
        id: user.id,
        name: user.userName,
        phone: user.personalPhone,
      },
      //客户
      client: orderInfo.clientDepart,
      //原订单信息
      _id: orderInfo._id,
      purchaseClassify: orderInfo.purchaseClassify,
      purchaseParts: orderInfo.purchaseParts,
      factory: orderInfo.factory,
      dataAuthority: orderInfo.dataAuthority,
      cities: orderInfo.cities,
      server: orderInfo.server,
      equipmentNo: orderInfo.equipmentNo,
      project: orderInfo.project
    }
   
    // console.log(param);

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.consignment(param).then(res=>{
      this.setData({
        disabled:false
      })
      if(res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })    
  },

  //查询订单信息
  getOrderInfo(){
    let param = {
      isAuth: false,
      className: 'partsPurchaseOrder',
      data: {
        id: this.data.paramObj.orderId,
        selectFields: ['id', 'cities', 'totalPurchasePrice', 'remark', 'server', 'staff', 'citiesName', 'freight','state', 'serverId', 'factoryName', 'address', 'purchasingTime', 'purchaseClassify', 'factoryId','operation', 'orderNo', 'contact', 'factory', 'reject', 'serverName', 'parts', 'logistics',
        'equipmentNo', 'salesperson', 'consignee', 'phone', 'clientDepart', 'shippedNum', 'outStorageType','inStorageType', 'dataAuthority', 'totalSalePrice', 'project', 'orderPersonnel', 'purchaseParts','approvalProcess', 'currentApprovalMan', 'purchaseApproval','logisticsParts','purchaseOrderId',]
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('采购订单信息');
        console.log(result);

        this.setData({
          orderInfo: result
        })

        //物流
        if(result.logisticsParts && result.logisticsParts.length){
          console.log('物流列表');
          console.log(result.logisticsParts);

          //把所有已发配件放入一个数组
          let arrs=[];
          result.logisticsParts.forEach(item => {
            item.parts.forEach(item2 => {
              arrs.push({
                code: item2.part.code,
                num: item2.num
              });
            });
          });           

          //按编码合并数量
          let listArr = [];
          arrs.forEach(function (el, index) {
            for (let i = 0; i < listArr.length; i++) {
              if (listArr[i].code == el.code) {
                listArr[i].num+=el.num;
                return;
              }
            }
            listArr.push({
              code: el.code,
              num: el.num
            });
          });

          //放入map中，方便匹配
          let map=new Map();
          listArr.forEach(item => {
            map.set(item.code,item.num);
          });

          console.log('已发配件数量');
          console.log(map);

          this.setData({
            sendNumMap: map
          })   
        }

        //采购的配件
        if(result.purchaseParts && result.purchaseParts.length){
          console.log('配件列表');
          console.log(result.purchaseParts);

          this.setData({
            partList: result.purchaseParts
          })
        }
        
      }
    }).catch((error) => {
    })
  },  

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  }, 

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //物流单号扫码
  onScanCode() {
    var _this = this;
    wx.scanCode({
      success: (res) => {
        let trackingNumber='editInfo.trackingNumber';
        _this.setData({
          [trackingNumber]: res.result
        })
      }
    })
  },
  
  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    let prevPage2 = pages[pages.length - 3];

    prevPage.refreshListAndPage();
    prevPage2.refreshListAndPage();
    wx.navigateBack();
  },  

  //显示时间
  onShowTime(){
    this.setData({
			showTime: true
    })
  },

  //隐藏时间
  onCloseTime(){
    this.setData({
			showTime: false
    })
  },

  //确认时间
  onConfirmTime(e) {
    let deliverTime='editInfo.deliverTime';
    let deliverTimeT='editInfo.deliverTimeT';
    this.setData({
      current: e.detail,
      [deliverTime]: util.timeFormat(e.detail),
      [deliverTimeT]: new Date(e.detail)
    })
    this.onCloseTime();
  },  

  //添加循环表单
  onAddLoop(){
    let list=this.data.loopList;

    //未填写不能加新的
    if(list.length){
      let len=list.length-1;
      if(list[len].name){
      }else{
        Toast.fail('当前配件信息未完成');
        return;
      }
    }

    list.push({
      name: null,
      part: null,
      num: 1,
      remark: null
    });

    this.setData({
      loopList: list,
      disabled: false
    })
  },

  //删除循环表单
  ondeleteLoop(e){
    Dialog.confirm({
      title: '确认删除此配件吗',
      confirmButtonText:'确认',
      cancelButtonText:'不删除了'
    }).then(() => {
      let list=this.data.loopList;
      let dataset=e.currentTarget.dataset;
      let arr=[];

      list.forEach((item,index) => {
        if(index!=dataset.index){
          arr.push(item);
        }
      });

      this.setData({
        loopList: arr
      })
    }).catch(() => {
    });
  },

  //获取输入的值
  onGetValue(e){
    let dataset=e.currentTarget.dataset;
    let val=e.detail;
    let list=this.data.loopList;

    list.forEach((item,index) => {
      if(index==dataset.index){
        item[dataset.field]=val.trim();
      }
    });

    this.setData({
      loopList: list,
      disabled: false
	  })
  },

  //获取数量
  onChangeNum(e) {
    let list=this.data.loopList;
    let dataset=e.currentTarget.dataset;

    list.forEach((item,index) => {
      if(index==dataset.index){
        item.num=e.detail;
      }
    });

    this.setData({
      loopList: list,
      disabled: false
    })
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //物流公司
    if(field=='logistics'){
      this.setData({
        selectTitle: '物流公司'
      })
      this.getLogCompanyList();
    }

    //配件
    if(field=='part'){
      this.setData({
        selectTitle: '配件',
        showSelectSearch: true,
        currentIndex: dataset.index,
        currentLoop: dataset.current
      }) 
      
      //处理配件选项
      let partList=this.data.partList;
      let sendNumMap=this.data.sendNumMap;
      let arr=[];

      partList.forEach(item => {
        item.part.purchaseNum = item.num;

        if(sendNumMap && sendNumMap.get(item.code)){
          item.part.max = item.num - sendNumMap.get(item.code);            
        }else{
          item.part.max = item.num;
        }

        if(item.part.max){
          arr.push({
            text: item.part.name,
            id: item.code,
            obj: item
          });
        }  
      });
     
      this.setData({
        selectList: arr
      })
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //物流公司
    if(selectField=='logistics'){
      obj='editInfo.logisticsCompany';
    }

    //配件
    if(selectField=='part'){
      let obj=e.detail.value.obj; 
      let currentIndex=this.data.currentIndex;
      let list=this.data.loopList;
      let flag=true;

      list.forEach((item,index) => {
        if(item.part && (item.part.partsCode==obj.code)){
          Toast.fail('已选择此配件，请修改数量');
          flag=false;
          return;
        }else{
          if(index==currentIndex){
            item.name = obj.name;
            item.part = {
              name: obj.part.name,
              code: obj.part.partsCode,
              max: obj.part.max,
              purchaseNum: obj.part.purchaseNum,
              unit: obj.part.unit
              // purchasePrice: obj.part.purchasePrice,
              // salePrice: obj.part.salePrice,              
              // category: obj.part.category,
              // param: obj.part.param,
              // spec: obj.part.spec  
            };
            item.category = obj.part.category;
            item.param = obj.part.param;
            item.spec = obj.part.spec;
            item.purchasePrice = obj.part.purchasePrice;
            item.salePrice = obj.part.salePrice;
          }
        }
      });

      //不能再选相同的配件
      if(flag){
        this.setData({
          loopList: list,
          disabled: false
        })
      }else{
        return;
      } 
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }
 
    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }
 
    this.onCloseSelect();
  },  

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //xxx
    if(selectField=='staff'){
      this.getXxxxxList();
    }
  },

  //查询物流公司
  getLogCompanyList(){
    let param = {
      isAuth: false,
      className: 'logisticsCompany',
      data: {
        searchAll: true,       
        selectFields: ['id','name','code']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj:{
              id: item.id,
              name: item.name,
              code: item.code
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  }, 

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})